package Server.Game.Questions;

import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;


import client.GUI.ErrorGui;

public class XMLReader extends DefaultHandler {
	private QuestionList questionL;
	String XmlFileName;
	String tmpValue;
	Question questionTmp;
	Answer answerTmp;
	boolean rightAnswer;

	public XMLReader(String XmlFileName) {
		this.XmlFileName = XmlFileName;
		setQuestionL(new QuestionList());
		parseDocument();
		
	}
	public void parseDocument() {
		SAXParserFactory factory = SAXParserFactory.newInstance();
		try {
			SAXParser parser = factory.newSAXParser();
			parser.parse(XmlFileName, this);
		} catch (ParserConfigurationException e) {
			new ErrorGui("ParserConfig error");
		} catch (SAXException e) {
			new ErrorGui("SAXException : xml not well formed");
		} catch (IOException e) {
			new ErrorGui("IO Error!");
		}
		
	}
	@Override
	public void startElement(String s, String s1, String elementName, Attributes attributes) throws SAXException {

		if (elementName.equalsIgnoreCase("kys")) {
			questionTmp = new Question();
		}
		if (elementName.equalsIgnoreCase("oiged")) {
			rightAnswer=true;
		}
		if (elementName.equalsIgnoreCase("valed")) {
			rightAnswer=false;
		}
	}
	@Override
	public void endElement(String s, String s1, String element) throws SAXException {
		if (element.equals("kys")) {
			getQuestionL().getQuestionList().add(questionTmp);
		}
		if (element.equalsIgnoreCase("kysimus")) {
			questionTmp.setContent(tmpValue);
		}
		if(element.equalsIgnoreCase("variant")){
			if(rightAnswer){
			questionTmp.addAnswer(new RightAnswer(tmpValue));
			}else{
			questionTmp.addAnswer(new WrongAnswer(tmpValue));	
			}
		}
	}
	@Override
	public void characters(char[] ac, int i, int j) throws SAXException {
		tmpValue = new String(ac, i, j);
	}

	public void setQuestionL(QuestionList questionL) {
		this.questionL = questionL;
	}
	public QuestionList getQuestionL() {
		return questionL;
	}
}